import axios from "axios";
import { ThunkAction } from "redux-thunk";
import { RootState } from '../index'
interface ListItem {
  url: string;
  title: string;
  word: string;
  id: string;
}

interface HomeState {
  data: ListItem[];
  loading: boolean;
  error: null | string;
}

const initState: HomeState = {
  data: [],
  loading: false,
  error: null,
};
const FETCH_START = "FETCH_START";
const FETCH_SUCCESS = "FETCH_SUCCESS";
const FETCH_FAIL = "FETCH_FAIL";

interface FetchStart {
  type: typeof FETCH_START;
}

export function fetchData(): ThunkAction<Promise<void>, RootState, any, HomeAction> {
  return async (dispatch) => {
    dispatch(fetchStartActionCreator());
    try {
      const resp = await axios.get("/api/list");
      dispatch(fetchSuccessActionCreator(resp.data.data));
    } catch (e: any) {
      dispatch(fetchFailActionCreator(e.message));
    }
  };
}

export function fetchStartActionCreator(): FetchStart {
  return { type: FETCH_START };
}

interface FetchSuccess {
  type: typeof FETCH_SUCCESS;
  payload: ListItem[];
}

export function fetchSuccessActionCreator(payload: ListItem[]): FetchSuccess {
  return { type: FETCH_SUCCESS, payload };
}

interface FetchFail {
  type: typeof FETCH_FAIL;
  payload: string;
}

export function fetchFailActionCreator(payload: string): FetchFail {
  return { type: FETCH_FAIL, payload };
}
export type HomeAction = FetchFail | FetchSuccess | FetchStart;

const HomeReducer = (state = initState, action: HomeAction) => {
  switch (action.type) {
    case FETCH_START:
      return {
        ...state,
        loading: true,
      };
    case FETCH_SUCCESS:
      return {
        ...state,
        loading: false,
        error: null,
        data: action.payload,
      };
    case FETCH_FAIL:
      return {
        ...state,
        loading: false,
        error: action.payload,
      };
    default:
      return state;
  }
};

export default HomeReducer;
